<template>
  <div>

    <el-card>
      <el-row :gutter="30">
        <el-col :span="5">
          <el-input v-model="lendSearchForm.readernumber" placeholder="借书卡" ></el-input>
        </el-col>
        <el-col :span="5">
          <el-input v-model="lendSearchForm.name" placeholder="图书名称" ></el-input>
        </el-col>
        <el-col :span="5">
          <el-select v-model="lendSearchForm.backtype" placeholder="请选择还书类型">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="success" icon="el-icon-search" @click="handleSearchLend" plain>搜索</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="warning" icon="el-icon-refresh-left" @click="resetSearch" plain>重置</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="primary" icon="el-icon-plus" @click="openLendDialog" plain>借书</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="danger" icon="el-icon-delete" @click="batchDeleteLendList" plain>删除</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card>
      <el-row>
        <el-table
            stripe
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%">
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              prop="name"
              label="图书名称"
              width="140">
          </el-table-column>
          <el-table-column
              prop="readernumber"
              label="借书卡"
              width="140">
          </el-table-column>
          <el-table-column
              prop="realname"
              label="借阅人"
              width="120">
          </el-table-column>
          <el-table-column
              prop="lenddate"
              label="借阅时间"
              width="160">
            <template slot-scope="scope">
              {{ formatDate(scope.row.lenddate) }}
            </template>
          </el-table-column>
          <el-table-column
              prop="backdate"
              label="还书时间"
              width="160">
            <template slot-scope="scope">
              {{ formatDate(scope.row.backdate) }}
            </template>
          </el-table-column>
          <el-table-column
              prop="backtype"
              label="还书类型"
              width="120">
            <template slot-scope="scope">
              <el-tag
                  :type="scope.row.backtype === 0 ?'success':(scope.row.backtype===1? 'primary' :(scope.row.backtype===2? 'info' : (scope.row.backtype===3? 'warning' : 'danger')))"
                  disable-transition>
                {{ scope.row.backtype === 0 ?'在借中':(scope.row.backtype===1? '正常还书': (scope.row.backtype===2? '延迟还书': (scope.row.backtype===3? '破损还书' : '丢失图书'))) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="145"
              header-align="center">
            <template slot-scope="scope">
              <div style="display: flex; justify-content: center;">
              <el-button @click="handleEdit(scope.row)" type="primary" plain icon="el-icon-edit" circle size="small"></el-button>
              <el-button type="danger" size="small" plain icon="el-icon-delete" circle @click="deleteLendList(scope.row)"></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row>
        <el-pagination
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="pageData.currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size=pageData.pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.total">
        </el-pagination>
      </el-row>
    </el-card>

    <el-dialog
        title="借书"
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleCloseLend">

      <el-form :model="lendForm" :rules="rules" ref="lendForm">
        <el-form-item label="图书名称" :label-width="formLabelWidth" prop="name">
          <el-select v-model="lendForm.name" filterable placeholder="请选择图书" style="width: 100%">
            <el-option
                v-for="item in optionsLibrary"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="借书卡号" :label-width="formLabelWidth" prop="readernumber">
          <el-select v-model="lendForm.readernumber" filterable placeholder="请选择借书卡号" style="width: 100%">
            <el-option
                v-for="item in optionsReadernumber"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="cancelDialog">取 消</el-button>
    <el-button type="primary" plain @click="subForm">确 定</el-button>
  </span>
    </el-dialog>

    <el-dialog
        title="还书"
        :visible.sync="handleClick"
        width="30%"
        :before-close="handleClose">
      <el-form :model="lendForm" ref="lendForm">
        <el-form-item label="还书类型" :label-width="formLabelWidth" prop="backtype">
      <el-select v-model="lendForm.backtype" placeholder="请选择还书类型" style="width: 100%">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="handleClick = false">取 消</el-button>
    <el-button type="primary" plain @click="confirmReturnBook">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "LendViews",
  data() {
    return {
      lendForm:{
        readernumber:'',
        name:'',
        bookid:'',
        readerid:'',
        lenddate:'',
        backdate:'',
        backtype:'',
        exceptremarks:''
      },
      formLabelWidth: '100px',
      bookNameMap: {},
      tableData: [],
      pageData:{
        currentPage:1,
        pageSize:5,
        total:0
      },
      optionsLibrary: [],
      optionsReadernumber: [],
      options: [{
        value: 0,
        label: '在借中'
      }, {
        value: 1,
        label: '正常还书'
      }, {
          value: 2,
          label: '延迟还书'
        }, {
          value: 3,
          label: '破损还书'
        }, {
          value: 4,
          label: '丢失图书'
      }],
      dialogVisible: false,
      handleClick:false,
      lendSearchForm:{
        readernumber:'',
        name:'',
        backtype:''
      },
      rules:{
        name: [
          { required: true, message: '请选择图书', trigger: 'blur' },
        ],
        readernumber: [
          { required: true, message: '请选择借书卡号', trigger: 'blur' },
        ],
      }
    }
  },
  created(){
    this.getLendList()
    this.fetchBookNames()
    this.fetchReaderNumbers()
  },
  methods:{
    resetForm(){
      this.lendForm = {
        readernumber: '',
        name: '',
        bookid: '',
        readerid: '',
        lenddate: '',
        backdate: '',
        backtype: '',
        exceptremarks: ''
      }
    },
    currentChange(val){
      this.pageData.currentPage=val
      this.getLendList()
    },
    sizeChange(val){
      this.pageData.pageSize=val
      this.getLendList()
    },
    handleSearchLend() {
      this.pageData.currentPage = 1
      this.getLendList()
    },
    async getLendList() {
        const params = {...this.pageData, ...this.lendSearchForm};
        const { data: res } = await this.$axios.get("lendList/getCustomLendList", { params });
        this.tableData = res.data.records;
        this.pageData.total = res.data.total;
    },
    subForm() {
      this.$refs.lendForm.validate(async (valid) => {
        if (valid) {
          try {
            this.lendForm.lenddate = this.getCurrentDate();
            this.lendForm.backtype = 0;
            this.lendForm.readerid = this.lendForm.readernumber;
            this.lendForm.bookid = this.lendForm.name;
            const { data: res } = await this.$axios.post("lendList/addLendList", this.lendForm);
            if (res.success) {
              this.$message.success('借书成功');
              this.dialogVisible = false;
              this.resetForm();
              this.isEditing = false;
              await this.getLendList();
            }
          } catch (error) {
            this.$message.error('借书失败');
          }
        } else {
          return false;
        }
      });
    },
    confirmReturnBook() {
      this.$refs.lendForm.validate(async (valid) => {
        if (valid) {
          try {
            this.lendForm.backdate = this.lendForm.backtype === 0 ? '' : this.getCurrentDate();
            const { data: res } = await this.$axios.post("lendList/updateLendList", this.lendForm);
            if (res.success) {
              this.$message.success('还书成功');
              this.handleClick = false;
              await this.getLendList();
            }
          } catch (error) {
            this.$message.error('还书失败');
          }
        } else {
          return false;
        }
      });
    },
    deleteLendList(row){
      this.$confirm('此操作将永久删除该借阅记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data:res}=await this.$axios.get("lendList/deleteById",{params:{id:row.id}})
        if (res.success){
          this.$message.success('删除成功')
          await this.getLendList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    batchDeleteLendList() {
      const selectedRows = this.$refs.multipleTable.selection;
      if (selectedRows.length === 0) {
        this.$message.warning('请选择要删除的借阅记录');
        return;
      }
      this.$confirm('此操作将永久删除选中的借阅记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const ids = selectedRows.map(row => row.id);
        const { data: res } = await this.$axios.post("lendList/batchDeleteLendList", ids);
        if (res.success) {
          this.$message.success('删除成功');
          await this.getLendList();
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    resetSearch() {
      this.lendSearchForm.readernumber = ''
      this.lendSearchForm.name = ''
      this.lendSearchForm.backtype = ''
      this.pageData.currentPage = 1;
      this.getLendList()
    },
    handleEdit(row){
      this.lendForm = { ...row };
      this.isEditing = true;
      this.handleClick = true;
    },
    async fetchBookNames() {
      try {
        const { data: res } = await this.$axios.get("bookInfo/getBookNames");
        this.optionsLibrary = res.data.map(book => ({
          value: book.id,
          label: book.name
        }));
      } catch (error) {
        console.error("获取图书名称失败", error);
      }
    },
    async fetchReaderNumbers() {
      try {
        const { data: res } = await this.$axios.get("reader/getReaderNumbers");
        this.optionsReadernumber = res.data.map(readerInfo => ({
          value: readerInfo.id,
          label: readerInfo.readernumber
        }));
      } catch (error) {
        console.error("获取读者卡号失败", error);
      }
    },
    openLendDialog() {
      this.resetForm();
      this.dialogVisible = true;
    },
    getCurrentDate() {
      const now = new Date();
      return now.toISOString();
    },
    handleCloseLend(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.resetForm();
            this.$refs.lendForm.clearValidate();
            this.dialogVisible = false;
            done();
          })
          .catch(_ => {});
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    cancelDialog() {
      this.resetForm(); // 重置表单数据
      this.$refs.lendForm.clearValidate();
      this.dialogVisible = false; // 关闭对话框
    },
    formatDate(dateString) {
      if (!dateString) {
        return '';
      }
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        timeZone: 'Asia/Shanghai',
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      });
    },
  }
}
</script>

<style scoped>

</style>